﻿Imports System.Text
Imports Kairyu.Extension

Public Class CreateDbCommandEventArgs
    Inherits System.EventArgs

    Public Sub New(ByVal cmd As IDbCommand)
        Me.New(String.Empty, cmd)
    End Sub

    Public Sub New(ByVal rootTableName As String, ByVal cmd As IDbCommand)
        Me.RootTableName = rootTableName
        Me.Command = cmd
    End Sub

    ''' <summary>
    ''' コマンド
    ''' </summary>
    ''' <value></value>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Property Command As IDbCommand

    ''' <summary>
    ''' ルートテーブルの名前
    ''' </summary>
    ''' <value></value>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Property RootTableName As String

    ''' <summary>
    ''' コマンド情報レベル
    ''' </summary>
    ''' <value></value>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Property CommandInfoLevel As InfoLevelEnum = InfoLevelEnum.Info

    Public Function GetRootInfo() As String
        Return If(String.IsNullOrEmpty(Me.RootTableName), String.Empty, String.Format("[{0}]", Me.RootTableName))
    End Function

    Public Function GetSqlInfo() As String
        Return Me.Command.CommandText
    End Function

    Private Function GetParameterInfo() As String
        If Me.Command.Parameters.Count = 0 Then Return String.Empty
        Dim s As New StringBuilder
        For Each prm As IDbDataParameter In (From el As IDbDataParameter In Me.Command.Parameters Order By el.ParameterName)
            s.Appenddelimiter(", ")
            s.AppendFormat("{0}={1}", prm.ParameterName, If(IsDBNull(prm.Value), "NULL", prm.Value.ToString))
        Next
        Return String.Format("/* {0} */", s.ToString)
    End Function

    Public Overrides Function ToString() As String
        Dim s As New StringBuilder
        Dim add As Action(Of String) =
            Sub(val)
                If String.IsNullOrEmpty(val) Then Return
                s.AppendDelimiter(Space(1))
                s.Append(val)
            End Sub

        add.Invoke(Me.GetRootInfo)
        add.Invoke(Me.GetSqlInfo)
        add.Invoke(Me.GetParameterInfo)

        Return s.ToString
    End Function

End Class
